package com.scs.application.modules.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.scs.application.core.model.TreeNode;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.enums.CertBusType;
import com.scs.application.modules.base.dto.CertTreeNodeDTO;
import com.scs.application.modules.base.dto.MaterialForCertTreeDTO;
import com.scs.application.modules.base.entity.*;
import com.scs.application.modules.base.mapper.CertificateRepoMapper;
import com.scs.application.modules.base.mapper.CertificateRequirementMapper;
import com.scs.application.modules.base.mapper.CertificateSummaryMapper;
import com.scs.application.modules.base.mapper.MaterialMapper;
import com.scs.application.modules.base.service.*;
import com.scs.application.modules.base.vo.HospitalMaterialSpecVO;
import com.scs.application.modules.cert.entity.CertificateHospitalBusiness;
import com.scs.application.modules.cert.entity.CertificateRepository;
import com.scs.application.modules.cert.service.CertificateHospitalBusinessService;
import com.scs.application.modules.cert.service.CertificateRepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 */
@Service
public class CertificateRepoServiceImpl implements CertificateRepoService, ApplicationRunner {

    @Autowired
    private CertificateRepoMapper certificateRepoMapper;

    @Autowired
    private CertificateRequirementMapper certificateRequirementMapper;

    @Autowired
    private CertificateSummaryMapper certificateSummaryMapper;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ManufacturerService manufacturerService;

    @Autowired
    private MaterialCatalogService materialCatalogService;

    @Autowired
    private HospitalMaterialService materialService;

    @Autowired
    private CertificateRepositoryService certificateRepositoryService;

    @Autowired
    private HospitalSupplierService hospitalSupplierService;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private CertificateHospitalBusinessService certificateHospitalBusinessService;

    @Override
    public List<TreeNode> treeForHospital(String hospitalId) {
        // 要求上传的资质
        List<CertificateRequirement> crList = certificateRequirementMapper.selectList(Wrappers.<CertificateRequirement>query().eq(StringUtils.isNotBlank(hospitalId),"hospital_id", hospitalId));
        Map<String, Long> crMap = crList.stream().collect(Collectors.toMap(o -> o.getBusinessTypeCode(), o -> o.getRequiredCnt(), (o1, o2) -> o1));

        // 已上传的资质
        List<CertificateSummary> csList = certificateSummaryMapper.selectList(Wrappers.<CertificateSummary>query().eq(StringUtils.isNotBlank(hospitalId),"hospital_id", hospitalId));
        // 没有品类的给默认品类
        if (!csList.isEmpty()) {
            csList.stream().filter(tmp -> StringUtils.isAnyEmpty(tmp.getCatalogId(),tmp.getCatalogName())).forEach(item -> item.setCatalogName("未分类").setCatalogId("0"));
        }
        Map<String, Integer> csMap = csList.stream().collect(Collectors.toMap(o -> o.getSupplierId() + o.getManufacturerId() + o.getCatalogId() + o.getMaterialId(), o -> o.getUploadedCnt(), (o1, o2) -> o1));

        Map<String, Integer> mapSupplierMfg = csList.stream().collect(Collectors.toMap(o -> o.getSupplierId() + o.getManufacturerId() , o -> o.getUploadedCnt(), (o1, o2) -> o1));

        List<HospitalMaterialSpecVO> vos = certificateRepoMapper.listHospiMatrSpec(hospitalId,UserUtils.isSupplier() ? UserUtils.getSupplierId() : null);
        // 没有品类的给默认品类
        if (!vos.isEmpty()) {
            vos.stream().filter(tmp -> StringUtils.isAnyEmpty(tmp.getCatalog1Id(),tmp.getCatalog1Name())).forEach(item -> item.setCatalog1Name("未分类").setCatalog1Id("0"));
        }

        // 先依据供应商分类

        List<TreeNode> supplierNodeList = Lists.newArrayList();
        Map<String, String> supplierMap = Maps.newHashMap();




        for (HospitalMaterialSpecVO vo : vos) {
            String supplierId = vo.getSupplierId();
            String supplierName = vo.getSupplierName();
            if (supplierMap.containsKey(supplierId)) {
                continue;
            }
            int uploadedCnt = csMap.getOrDefault(supplierId + null + null + null, 0);
            supplierMap.put(supplierId, supplierName);
            TreeNode node = new TreeNode();
            node.setId("sp-" + supplierId);
            node.setTitle(supplierName);
            node.setParentId("0");
            node.addProperty("requireCnt", crMap.getOrDefault(CertBusType.SUPPLIER.getValue(), 0L));
            node.addProperty("uploadedCnt", uploadedCnt);
            node.addProperty("id", vo.getSupplierId());

            supplierNodeList.add(node);
        }

        // 添加厂商节点
        List<TreeNode> allMfgNodeList = Lists.newArrayList();
        for (TreeNode treeNode : supplierNodeList) {
            List<TreeNode> children = treeNode.getChildren();
            if (children == null) {
                children = new ArrayList<>();
            }
            Map mfgMap = Maps.newHashMap();


            List<HospitalMaterialSpecVO> mfgList = vos.stream().filter(o -> {
                return treeNode.getProperties().get("id").toString().equalsIgnoreCase(o.getSupplierId());
            }).collect(Collectors.toList());
            for (HospitalMaterialSpecVO vo : mfgList) {
                String manufacturerId = vo.getManufacturerId();
                String manufacturerName = vo.getManufacturerName();

//                int uploadedCnt = mapSupplierMfg.getOrDefault(vo.getSupplierId() + manufacturerId + null + null, 0);
                int uploadedCnt = csMap.getOrDefault(vo.getSupplierId() + manufacturerId + null + null, 0);
                if (!mfgMap.containsKey(manufacturerId)) {
                    TreeNode node = new TreeNode();
                    node.setId(vo.getSupplierId() + "mfg-" + manufacturerId);
                    node.setTitle(manufacturerName);
                    node.setParentId(treeNode.getId());
                    node.addProperty("requireCnt", crMap.getOrDefault(CertBusType.MANUFACTURER.getValue(), 0L));
                    node.addProperty("uploadedCnt", uploadedCnt);
                    node.addProperty("supplierId", vo.getSupplierId());
                    node.addProperty("id", manufacturerId);
                    children.add(node);
                }
                mfgMap.put(manufacturerId, manufacturerName);
            }
            if (!children.isEmpty()) {
                treeNode.setChildren(children);
            }
            treeNode.getProperties().remove("id");
            allMfgNodeList.addAll(children);
        }

        //  添加品类节点
        List<TreeNode> allCatalogNodeList = Lists.newArrayList();

        for (TreeNode treeNode : allMfgNodeList) {
            List<TreeNode> children = treeNode.getChildren();
            if (children == null) {
                children = new ArrayList<>();
            }
            Map caalog1Map = Maps.newHashMap();

            String supplierId = (String) treeNode.getProperties().get("supplierId");
            String manufacturerId = (String) treeNode.getProperties().get("id");

            List<HospitalMaterialSpecVO> catalog1List = vos.stream().filter(o -> {
                // 依据供应商ID+厂商ID进行筛选
                return (supplierId + manufacturerId).equalsIgnoreCase(o.getSupplierId() + o.getManufacturerId());
            }).collect(Collectors.toList());
            for (HospitalMaterialSpecVO vo : catalog1List) {
                String catalog1Id = vo.getCatalog1Id();
                String catalog1Name = vo.getCatalog1Name();
                int uploadedCnt = csMap.getOrDefault(vo.getSupplierId() + manufacturerId + catalog1Id + null, 0);

                // 没有品类
//                if (StringUtils.isBlank(catalog1Name)) {
//                    if (caalog1Map.containsKey(catalog1Id)) {
//                        continue;
//                    }
//                    catalog1Id="-1";
//                    catalog1Name="无品类";
//                    TreeNode node = new TreeNode();
//                    node.setId(vo.getSupplierId() + vo.getManufacturerId() + "mc-" + catalog1Id);
//                    node.setTitle(catalog1Name);
//                    node.setParentId(treeNode.getId());
//                    node.addProperty("requireCnt", crMap.getOrDefault(CertBusType.CATALOG.getValue(), 0L));
//                    node.addProperty("uploadedCnt", uploadedCnt);
//                    node.addProperty("supplierId", supplierId);
//                    node.addProperty("manufacturerId", manufacturerId);
//                    node.addProperty("id", 0);
//                    children.add(node);
//                    caalog1Map.put(catalog1Id, catalog1Name);
//                    vo.setCatalog1Id(catalog1Id);
//                    vo.setCatalog1Name(catalog1Name);
//                    continue;
//                }


                if (!caalog1Map.containsKey(catalog1Id)) {
                    TreeNode node = new TreeNode();
                    node.setId(vo.getSupplierId() + vo.getManufacturerId() + "mc-" + catalog1Id);
                    node.setTitle(catalog1Name);
                    node.setParentId(treeNode.getId());
                    node.addProperty("requireCnt", crMap.getOrDefault(CertBusType.CATALOG.getValue(), 0L));
                    node.addProperty("uploadedCnt", uploadedCnt);
                    node.addProperty("supplierId", supplierId);
                    node.addProperty("manufacturerId", manufacturerId);
                    node.addProperty("id", catalog1Id);
                    children.add(node);
                }
                caalog1Map.put(catalog1Id, catalog1Name);
            }
            if (!children.isEmpty()) {
                treeNode.setChildren(children);
            }
            allCatalogNodeList.addAll(children);
            /*treeNode.getProperties().remove("supplierId");*/
            treeNode.getProperties().remove("id");
        }

        //  添加耗材节点
        List<TreeNode> allMaterialNodeList = Lists.newArrayList();

        for (TreeNode treeNode : allCatalogNodeList) {
            List<TreeNode> children = treeNode.getChildren();
            if (children == null) {
                children = new ArrayList<>();
            }
            Map materialMap = Maps.newHashMap();

            String supplierId = (String) treeNode.getProperties().get("supplierId");
            String manufacturerId = (String) treeNode.getProperties().get("manufacturerId");
            String catalog1Id = treeNode.getProperties().get("id") + "";

            List<HospitalMaterialSpecVO> catalog1List = vos.stream().filter(o -> {
                // 依据供应商ID+厂商ID+品类ID进行筛选
                return (supplierId + manufacturerId + catalog1Id).equalsIgnoreCase(
                        o.getSupplierId() + o.getManufacturerId() + o.getCatalog1Id());
            }).collect(Collectors.toList());
            for (HospitalMaterialSpecVO vo : catalog1List) {
                String materialId = vo.getMaterialId();
                String materialName = vo.getMaterialName();

                int uploadedCnt = csMap.getOrDefault(vo.getSupplierId() + manufacturerId + catalog1Id + materialId, 0);
                if (!materialMap.containsKey(materialId)) {
                    TreeNode node = new TreeNode();
                    node.setId("matr-" + materialId);
                    node.setTitle(materialName);
                    node.setParentId(treeNode.getId());
                    node.addProperty("requireCnt", crMap.getOrDefault(CertBusType.MATERIAL.getValue(), 0L));
                    node.addProperty("uploadedCnt", uploadedCnt);
                    children.add(node);
                }
                materialMap.put(materialId, materialName);
            }
            if (!children.isEmpty()) {
                treeNode.setChildren(children);
            }
            allMaterialNodeList.addAll(children);
            /*treeNode.getProperties().remove("supplierId");
            treeNode.getProperties().remove("manufacturerId");*/
            treeNode.getProperties().remove("id");
        }

        return supplierNodeList;
    }

    /***
     * @param
     * @Author: Tai
     * @date: 2024/6/24
     * @Description:  供应商、厂商、品类、品名
     */
    @Override
    public List<CertTreeNodeDTO> getCertTree(String queryType,String supplierIdFilter) {
        certificateRepoMapper.updateByMaterialChange();
        CertTreeNodeDTO nodeSp = null;
        List<CertTreeNodeDTO> nodeRoot = new ArrayList<>();
        List<Manufacturer> mfgListBySp;
        String hospitalId = null,supplierId = null;
        Boolean isSp = false;
        Boolean isHp = false;
        try {
            isSp = UserUtils.isSupplier();
        }catch (Exception e) {
        }
        try {
            isHp = UserUtils.isHospital();
        }catch (Exception e) {
        }
        if (!UserUtils.isAdmin()) {
            if(UserUtils.isHospital()) {
                hospitalId = UserUtils.getHospitalId();
            }
            if (UserUtils.isSupplier()) {
                supplierId = UserUtils.getSupplierId();
            }
        }
        QueryWrapper<Supplier> queryWrapperSp = new QueryWrapper<>();
        if (!UserUtils.isAdmin()) {
            // 只筛选有供货关系的医院
            if (UserUtils.isSupplier()) {
                queryWrapperSp.eq("id", supplierId);
            } else {
                queryWrapperSp.orderByAsc("name");
            }
            // 只筛选当前医院有供货关系的供应商
            if (UserUtils.isHospital()) {
                List<HospitalSupplier> spList = hospitalSupplierService.list(Wrappers.<HospitalSupplier>query().eq("hospital_id", hospitalId));
                if (!spList.isEmpty()) {
                    queryWrapperSp.in("id", spList.stream().map(HospitalSupplier::getSupplierId).distinct().collect(Collectors.toList()));
                }else {
                    queryWrapperSp.eq("1","0");
                }
            }
        }
        if (StringUtils.isNotBlank(supplierIdFilter)) {
            queryWrapperSp.eq("id",supplierIdFilter);
        }

        // 供应商
        List<Supplier> spList = supplierService.list(queryWrapperSp);
        if (spList.isEmpty()) {
            return null;
        }

        List<String> spIdList = spList.stream().map(Supplier::getId).collect(Collectors.toList());

        QueryWrapper<Material> queryWrapperCertTree = Wrappers.<Material>query();
        if (spIdList.size() == 0) {
            return nodeRoot;
        }
        if (spIdList.size() == 1) {
            queryWrapperCertTree.eq("supplier_id",spIdList.get(0));
        }else{
            queryWrapperCertTree.in("supplier_id",spIdList);
        }

        // 商品列表
        List<MaterialForCertTreeDTO> materialList =  materialMapper.listForCertTree(queryWrapperCertTree);
        if (materialList.isEmpty()) {
            return nodeRoot;
        }
        // 没有品类的给默认品类
        materialList.stream().filter(tmp -> StringUtils.isAnyEmpty(tmp.getCatalogId(),tmp.getCatalogName())).forEach(item -> item.setCatalogName("未分类").setCatalogId("0"));
        Map<String,MaterialForCertTreeDTO> catById = materialList.stream().collect(Collectors.toMap(MaterialForCertTreeDTO::getCatalogId, tmp -> tmp, (left ,right) -> left));

        // 厂商
        List<Manufacturer> mfgList = manufacturerService.list(Wrappers.<Manufacturer>query()
                .in("supplier_id",spIdList)
                .inSql("id",StrUtil.format(" select manufacturer_id from material"))
                .orderByAsc("name")
        );
        Map<String,List<Manufacturer>> mfgBySpId = new HashMap<>();;
        if (!mfgList.isEmpty()) {
            mfgBySpId = mfgList.stream().collect(Collectors.groupingBy(Manufacturer::getSupplierId));
        }

        // 资质列表
        QueryWrapper<CertificateRepository> queryWrapperCert = Wrappers.<CertificateRepository>query().ne("close_flag",CertificateRepository.CLOSE_FLAG_CLOSED).in("supplier_id",spIdList);
        //查看时，只显示已提交的
        if ("view".equals(queryType)) {
            queryWrapperCert.eq("submit_flag", CertificateRepository.SUBMIT_FLAG_SUBMITED);
        }
        // 医院角色时，只筛选该医院定义的资质，如果存在的话
        if (isHp) {
            List<CertificateHospitalBusiness> certificateHospitalBusinessList = certificateHospitalBusinessService
                    .list(Wrappers.<CertificateHospitalBusiness>query()
                            .eq("hospital_id",UserUtils.getHospitalId()));
            if (!certificateHospitalBusinessList.isEmpty()) {
                queryWrapperCert.in(
                        "certificate_id",
                        certificateHospitalBusinessList.stream().map(CertificateHospitalBusiness::getCertificateId).collect(Collectors.toList())
                );
            }
        }
        List<CertificateRepository> certList = certificateRepositoryService.list(queryWrapperCert);
        if (certList == null) {
            certList = new ArrayList<>();
        }
        if (!certList.isEmpty()){
            Date dateNow = DateUtils.now();
            certList.forEach(item -> {
                if (item.getExpiryDate() != null) {
                    item.setFlagDateOver(DateUtils.diffDate(dateNow,item.getExpiryDate()) <= 30 ? 1 : 0);
                }else {
                    item.setFlagDateOver(0);
                }
            });
        }


        // 遍历供应商
        long numDayOver = 0, numSubmited= 0;
        List<CertificateRepository> certListSp;
        for(Supplier supplier : spList) {
            mfgListBySp = mfgBySpId.get(supplier.getId());
            certListSp = certList.stream().filter(tmp -> tmp.getSupplierId().equals(supplier.getId())).collect(Collectors.toList());
            numDayOver = certListSp.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag() && tmp.getFlagDateOver() == 1).count();
            if ("warn".equals(queryType) && numDayOver == 0) {
                continue;
            }

            numSubmited = certListSp.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag()).count();
            if ("view".equals(queryType) && numSubmited == 0) {
                continue;
            }
            nodeSp = new CertTreeNodeDTO();
            nodeSp.setId(supplier.getId()).setTargetDescribeId(supplier.getId())
                    .setTypeName(CertTreeNodeDTO.TypeNameList.sp).setTypeNameSub(CertTreeNodeDTO.TypeNameList.mfg).setTitle(supplier.getName());

            nodeSp.setNumUnSubmit(certListSp.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_UNSUBMIT ==  tmp.getSubmitFlag()).count())
                    .setNumSubmited(numSubmited)
                    .setNumDayOver(numDayOver)
                    .setSpId(supplier.getId()).setSpName(supplier.getName())
                    .setChildren(
                            getChildrenSp(
                                    queryType,
                                    nodeSp,
                                    // 该企业的相关商品
                                    materialList.stream().filter(tmp -> tmp.getSupplierId().equals(supplier.getId())).collect(Collectors.toList()),
                                    // 该企业的相关资质
                                    certListSp.stream().filter(tmp -> !tmp.getBusinessTypeCode().equals(CertBusType.SUPPLIER.getValue())).collect(Collectors.toList()),
                                    catById,
                                    mfgListBySp,
                                    supplier
                            )
                    )
            ;
            nodeRoot.add(nodeSp);
        }
        return nodeRoot;
    }

    /***
     * @Description:  获取供应商子节点
     * @param nodeParent            上级节点
     * @param catById               商品分类
     * @param materialList          该供应商的相关商品
     * @param mfgListBySp           该供应商的相关厂商
     * @param supplier              供应商
     */
    private List<CertTreeNodeDTO> getChildrenSp(
            String queryType,
            CertTreeNodeDTO nodeParent,
            List<MaterialForCertTreeDTO> materialList,
            List<CertificateRepository> certList,
            Map<String,MaterialForCertTreeDTO> catById,
            List<Manufacturer> mfgListBySp,Supplier supplier
    ) {
        if (mfgListBySp == null || mfgListBySp.isEmpty()) {
            return null;
        }
        List<CertTreeNodeDTO> nodeMfgList = new ArrayList<>();
        List<String> catIdList;
        CertTreeNodeDTO nodeMfg;
        long numDayOver = 0,numSubmited = 0;

        // 遍历厂商
        List<CertificateRepository> certListMfg;
        for(Manufacturer mfg : mfgListBySp) {
            certListMfg = certList.stream().filter(tmp ->   mfg.getId().equals(tmp.getManufacturerId())).collect(Collectors.toList());
            numDayOver = certListMfg.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag() && tmp.getFlagDateOver() == 1).count();
            if ("warn".equals(queryType) && numDayOver == 0) {
                continue;
            }
            numSubmited = certListMfg.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag()).count();
            if ("view".equals(queryType) && numSubmited == 0) {
                continue;
            }

            // 该厂商的所有分类
            catIdList = materialList.stream().filter(tmp -> mfg.getId().equals(tmp.getManufacturerId()) )
                    .map(MaterialForCertTreeDTO::getCatalogId).distinct().collect(Collectors.toList());
            if (catIdList.isEmpty()) {
                continue;
            }

            nodeMfg = new CertTreeNodeDTO();
            nodeMfg.setId(StrUtil.format("{}_{}",nodeParent.getId(),mfg.getId())).setTargetDescribeId(mfg.getId())
                    .setTypeName(CertTreeNodeDTO.TypeNameList.mfg).setTypeNameSub(CertTreeNodeDTO.TypeNameList.cat).setTitle(mfg.getName());
            nodeMfg.setNumUnSubmit(certListMfg.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_UNSUBMIT ==  tmp.getSubmitFlag()).count())
                    .setNumSubmited(numSubmited)
                    .setNumDayOver(numDayOver)
                    .setSpId(supplier.getId()).setSpName(supplier.getName()).setMfgId(mfg.getId()).setMfgName(mfg.getName())
                    .setChildren(getChildrenMfg(
                            queryType,
                            nodeMfg,
                            // 该厂商的相关商品
                            materialList.stream().filter(tmp ->  mfg.getId().equals(tmp.getManufacturerId()) ).collect(Collectors.toList()),
                            // 该厂商的相关资质
                            certListMfg.stream().filter(tmp -> !tmp.getBusinessTypeCode().equals(CertBusType.MANUFACTURER.getValue())).collect(Collectors.toList()),
                            catById,
                            catIdList,
                            supplier,
                            mfg
                    ))
            ;
            nodeMfgList.add(nodeMfg);
        }
        return nodeMfgList;
    }

    /***
     * @Description:  获取厂商子节点
     * @param nodeParent            上级节点
     * @param catById               商品分类
     * @param materialList      该供应商该厂商的相关商品
     * @param catIdList             该厂商的相关商品分类
     * @param supplier              供应商
     */
    private List<CertTreeNodeDTO> getChildrenMfg(
            String queryType,
            CertTreeNodeDTO nodeParent,
            List<MaterialForCertTreeDTO> materialList,
            List<CertificateRepository> certList,
            Map<String,MaterialForCertTreeDTO> catById,
            List<String> catIdList,Supplier supplier,
            Manufacturer mfg)
    {
        if (catIdList == null || catIdList.isEmpty()) {
            return null;
        }
        List<CertTreeNodeDTO> nodeMfgList = new ArrayList<>();
        List<CertTreeNodeDTO> nodeMatrList;
        List<MaterialForCertTreeDTO> matrFindList;
        CertTreeNodeDTO nodeCat,nodeMatr;

        long numDayOver = 0, numSubmited = 0;

        List<CertificateRepository> certListCat;
        List<CertificateRepository> certListMatr;
        for(String catId : catIdList) {
            certListCat = certList.stream().filter(tmp ->   catId.equals(tmp.getCatalogId())).collect(Collectors.toList());
            numDayOver = certListCat.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag()  && tmp.getFlagDateOver() == 1).count();
            if ("warn".equals(queryType) && numDayOver == 0) {
                continue;
            }
            numSubmited = certListCat.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag()).count();
            if ("view".equals(queryType) && numSubmited == 0) {
                continue;
            }

            if (mfg.getId().equals("1836695827423789057") && catId.equals("0")) {
                System.out.println("调试");
            }


            // 该分类的所有商品
            matrFindList = materialList.stream().filter(tmp ->
                            catId.equals(tmp.getCatalogId())
                    )
                    .collect(Collectors.toList());
            nodeMatrList = new ArrayList<>();
            nodeCat = new CertTreeNodeDTO();
            nodeCat.setId(StrUtil.format("{}_{}",nodeParent.getId(),catId)).setTargetDescribeId(catId)
                    .setTypeName(CertTreeNodeDTO.TypeNameList.cat).setTypeNameSub(CertTreeNodeDTO.TypeNameList.matr).setTitle(catById.get(catId).getCatalogName());
            nodeCat.setNumUnSubmit(certListCat.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_UNSUBMIT ==  tmp.getSubmitFlag()).count())
                    .setNumSubmited(numSubmited)
                    .setNumDayOver(numDayOver)
                    .setSpId(supplier.getId()).setSpName(supplier.getName()).setMfgId(mfg.getId()).setMfgName(mfg.getName()).setCatId(catId).setCatName(catById.get(catId).getCatalogName())
            ;


            // 遍历商品
            if (!matrFindList.isEmpty()) {
                for(MaterialForCertTreeDTO matr : matrFindList) {
                    certListMatr = certListCat.stream().filter(tmp ->   matr.getMaterialId().equals(tmp.getMaterialId())).collect(Collectors.toList());
                    numDayOver = certListMatr.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag() && tmp.getFlagDateOver() == 1).count();
                    if ("warn".equals(queryType) && numDayOver == 0) {
                        continue;
                    }
                    numSubmited = certListMatr.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_SUBMITED ==  tmp.getSubmitFlag()).count();
                    if ("view".equals(queryType) && numSubmited == 0) {
                        continue;
                    }

                    nodeMatr = new CertTreeNodeDTO();
                    nodeMatr.setId(StrUtil.format("{}_{}",nodeCat.getId(),matr.getMaterialId())).setTargetDescribeId(matr.getMaterialId())
                            .setTypeName(CertTreeNodeDTO.TypeNameList.matr).setTitle(matr.getMaterialName());

                    nodeMatr.setNumUnSubmit(certListMatr.stream().filter(tmp ->  CertificateRepository.SUBMIT_FLAG_UNSUBMIT ==  tmp.getSubmitFlag()).count())
                            .setNumSubmited(numSubmited)
                            .setNumDayOver(numDayOver)
                            .setSpId(supplier.getId()).setSpName(supplier.getName()).setMfgId(mfg.getId()).setMfgName(mfg.getName()).setCatId(catId).setCatName(catById.get(catId).getCatalogName())
                            .setMatrId(matr.getMaterialId()).setMatrName(matr.getMaterialName())

                    ;
                    nodeMatrList.add(nodeMatr);
                }
            }
            nodeCat.setChildren(nodeMatrList);
            nodeMfgList.add(nodeCat);
        }
        return nodeMfgList;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        certificateRepoMapper.updateByMaterialChange();
    }
}
